
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>

int main()
{
    pid_t id = fork();
    if(id == 0)
    {
        //子进程
        int cnt = 5;
        while(cnt)
        {
             printf("我是子进程：%d，父进程：%d，cnt=%d\n",getpid(),getppid(),cnt--);
             sleep(2);
            // int* p = NULL;
            // *p = 10;
        }
        exit(10);//进程退出
    }
    //父进程
    int status = 0;
    while(1)
    {
        pid_t ret = waitpid(id, &status, WNOHANG);                                                                         
        if(ret > 0)                                                                                                        
        {                                                                                                                  
            //waitpid调用成功 && 子进程退出了
            printf("wait success: %d, sig number: %d, child exit code: %d\n",ret, (status & 0x7F), ((status >> 8) & 0xFF));
            break;
        }                                                                  
        else if(ret == 0)                                                  
        {                                                                  
            //waitpid调用成功 && 子进程没退出
            //waitpid没有等待失败，只是子进程没退出，仅仅检测到子进程没退出
            printf("子进程仍在运行\n");
            sleep(1);
        }                                                                                                                         
        else                                                                                                                      
        {                                                                                                                         
            //waitpid调用失败                                                                                                     
            printf("waitpid call filed\n");
            break;
        }
    }

    return 0;
}
